import React, {useEffect} from 'react';
import {useParams} from 'react-router-dom';
import {Button, Card, Col, Descriptions, Divider, Row, Space, Spin, Tag, Typography} from 'antd';
import {
    BookOutlined,
    ClockCircleOutlined,
    ShoppingOutlined,
    PlayCircleOutlined,
    ShoppingCartOutlined,
    UserOutlined
} from '@ant-design/icons';
import { useCart } from '../hooks/useCart';
import {useQuery} from '@tanstack/react-query';
import {getCourseDetail} from '../api/divide/course/sdk.gen';

const {Title, Paragraph, Text} = Typography;


const CourseDetail: React.FC = () => {
    const {id} = useParams<{ id: string }>();
    const courseId = id ? parseInt(id, 10) : 0;

    // 页面加载时滚动到顶部
    useEffect(() => {
        window.scrollTo(0, 0);
    }, [courseId]); // 当courseId变化时也重置滚动位置

    const {data: courseData, isLoading, error} = useQuery({
        queryKey: ['courseDetail', courseId],
        queryFn: () => getCourseDetail({
            path: {id: courseId}
        }),
        enabled: courseId > 0,
    });

    const { addToCart, isAdding } = useCart();

    // ... 其余代码保持不变

    const course = courseData?.data?.data;

    const getLevelColor = (level: string) => {
        switch (level) {
            case '初级':
                return 'green';
            case '中级':
                return 'orange';
            case '高级':
                return 'red';
            default:
                return 'blue';
        }
    };

    const getStatusColor = (status: string) => {
        switch (status) {
            case '上架':
                return 'success';
            case '下架':
                return 'error';
            default:
                return 'default';
        }
    };

    if (isLoading) {
        return (
            <div style={{padding: 24, textAlign: 'center'}}>
                <Spin size="large"/>
            </div>
        );
    }

    if (error || !course) {
        return (
            <div style={{padding: 24}}>
                <Card>
                    <div style={{textAlign: 'center', padding: 100}}>
                        <h2>课程不存在或加载失败</h2>
                        <p>请返回课程列表重新选择</p>
                    </div>
                </Card>
            </div>
        );
    }

    return (
        <div style={{padding: '540px 24px 24px 0'}}>
            <Row gutter={[24, 24]}>
                {/* 课程封面和基本信息 */}
                <Col xs={24} lg={8}>
                    <Card>
                        <div style={{
                            width: '100%',
                            height: 300,
                            backgroundColor: '#f0f2f5',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            marginBottom: 16,
                            borderRadius: 8,
                            overflow: 'hidden'
                        }}>
                            {course.coverImage ? (
                                <img
                                    alt={course.title}
                                    src={course.coverImage}
                                    style={{width: '100%', height: '100%', objectFit: 'cover'}}
                                />
                            ) : (
                                <div style={{color: '#999', fontSize: 16}}>暂无课程封面</div>
                            )}
                        </div>

                        <Space direction="vertical" size="large" style={{width: '100%'}}>
                            <div>
                                <Title level={4} style={{marginBottom: 8}}>{course.title}</Title>
                                <Space>
                                    <Tag color={getLevelColor(course.level || '')}>
                                        <BookOutlined/> {course.level}
                                    </Tag>
                                    <Tag color={getStatusColor(course.status || '')}>
                                        {course.status}
                                    </Tag>
                                </Space>
                            </div>

                            <div>
                                <Text style={{fontSize: 24, fontWeight: 600, color: '#ff4d4f'}}>
                                    ¥{course.price}
                                </Text>
                            </div>

                            <Space direction="vertical" style={{width: '100%'}}>
                                <Button 
                                    type="primary" 
                                    size="large" 
                                    icon={<ShoppingCartOutlined/>} 
                                    block
                                    loading={isAdding}
                                    onClick={() => {
                                        addToCart({
                                            courseId: course.id!,
                                            quantity: 1
                                        });
                                    }}
                                >
                                    加入购物车
                                </Button>
                                <Button icon={<ShoppingOutlined/>} block>
                                    立即购买
                                </Button>
                                <Button type="dashed" icon={<PlayCircleOutlined/>} block>
                                    立即学习
                                </Button>
                            </Space>
                        </Space>
                    </Card>
                </Col>

                {/* 课程详细信息 */}
                <Col xs={24} lg={16}>
                    <Card>
                        <Title level={3}>课程详情</Title>

                        <Descriptions column={2} bordered style={{marginBottom: 24}}>
                            <Descriptions.Item label="课程时长">
                                <Space>
                                    <ClockCircleOutlined/>
                                    {course.duration} 分钟
                                </Space>
                            </Descriptions.Item>
                            <Descriptions.Item label="课程讲师">
                                <Space>
                                    <UserOutlined/>
                                    讲师 #{course.instructorId}
                                </Space>
                            </Descriptions.Item>
                            <Descriptions.Item label="库存数量">
                                {course.stock || '不限'}
                            </Descriptions.Item>
                            <Descriptions.Item label="已售数量">
                                {course.soldCount || 0} 份
                            </Descriptions.Item>
                            <Descriptions.Item label="限购数量">
                                {course.maxPurchasePerUser || '不限'} 份/人
                            </Descriptions.Item>
                            <Descriptions.Item label="是否限时">
                                {course.limitedStock ? '是' : '否'}
                            </Descriptions.Item>
                        </Descriptions>

                        <Divider orientation="left">课程描述</Divider>
                        <Paragraph style={{fontSize: 16, lineHeight: 1.8}}>
                            {course.description || '暂无详细描述'}
                        </Paragraph>

                        {course.saleStartTime && course.saleEndTime && (
                            <>
                                <Divider orientation="left">销售时间</Divider>
                                <Descriptions column={1} bordered>
                                    <Descriptions.Item label="开始时间">
                                        {new Date(course.saleStartTime).toLocaleString('zh-CN')}
                                    </Descriptions.Item>
                                    <Descriptions.Item label="结束时间">
                                        {new Date(course.saleEndTime).toLocaleString('zh-CN')}
                                    </Descriptions.Item>
                                </Descriptions>
                            </>
                        )}

                        <Divider orientation="left">课程统计</Divider>
                        <Row gutter={16}>
                            <Col span={8}>
                                <Card size="small">
                                    <Statistic
                                        title="总销量"
                                        value={course.soldCount || 0}
                                        prefix={<ShoppingCartOutlined/>}
                                    />
                                </Card>
                            </Col>
                            <Col span={8}>
                                <Card size="small">
                                    <Statistic
                                        title="课程评分"
                                        value={4.8}
                                        precision={1}
                                        prefix={<StarOutlined/>}
                                        suffix="/ 5.0"
                                    />
                                </Card>
                            </Col>
                            <Col span={8}>
                                <Card size="small">
                                    <Statistic
                                        title="学习人数"
                                        value={Math.floor((course.soldCount || 0) * 0.85)}
                                        prefix={<UserOutlined/>}
                                    />
                                </Card>
                            </Col>
                        </Row>
                    </Card>

                    {/* 课程章节（预留位置） */}
                    <Card style={{marginTop: 24}}>
                        <Title level={4}>课程章节</Title>
                        <div style={{textAlign: 'center', padding: 40, color: '#999'}}>
                            <BookOutlined style={{fontSize: 48, marginBottom: 16}}/>
                            <p>课程章节内容正在准备中...</p>
                        </div>
                    </Card>

                    {/* 讲师信息（预留位置） */}
                    <Card style={{marginTop: 24}}>
                        <Title level={4}>讲师信息</Title>
                        <div style={{textAlign: 'center', padding: 40, color: '#999'}}>
                            <UserOutlined style={{fontSize: 48, marginBottom: 16}}/>
                            <p>讲师详细信息正在整理中...</p>
                        </div>
                    </Card>
                </Col>
            </Row>
        </div>
    );
};

// 补充Statistic组件
const Statistic: React.FC<{
    title: string;
    value: number | string;
    precision?: number;
    prefix?: React.ReactNode;
    suffix?: string;
}> = ({title, value, precision, prefix, suffix}) => (
    <div style={{textAlign: 'center'}}>
        <div style={{color: '#666', marginBottom: 4}}>{title}</div>
        <div style={{fontSize: 20, fontWeight: 600, color: '#1890ff'}}>
            {prefix}
            {typeof value === 'number' && precision ? value.toFixed(precision) : value}
            {suffix}
        </div>
    </div>
);

const StarOutlined: React.FC<{ style?: React.CSSProperties }> = ({style}) => (
    <span style={{...style, color: '#faad14'}}>★</span>
);

export default CourseDetail;